package com.epoint.mobileoa.personalized.epointcompany.ui.kaoqing;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ListView;

import com.epoint.mobileoa.R;
import com.epoint.mobileoa.bizlogic.ConfigKey;
import com.epoint.mobileoa.bizlogic.SuperView;
import com.epoint.mobileoa.bmap.BMap_GPS_Extent;
import com.epoint.mobileoa.db.DBHelp;
import com.epoint.mobileoa.personalized.epointcompany.bizlogic.KaoQingTask;
import com.epoint.mobileoa.personalized.epointcompany.ui.kaoqing.GPSHelper.GPSCallBack;
import com.epoint.mobileoa.service.MainService;
import com.epoint.mobileoa.tools.AlertHelp;
import com.epoint.mobileoa.tools.LogHelp;
import com.epoint.mobileoa.tools.ToastHelp;

public class KaoQingView extends SuperView implements GPSCallBack {

	private final String GET_LOCATION = "get_location";
	private final String KAOQING = "kaoqing";

	private WebView webView;
	private Button kaoQing;
	private GPSInfo gpsInfo;
	private ListView recards;
	private RecardsAdapter adapter;
	private List<KaoQingInfo> data;
	private GPSHelper gpsHelper;

	private String reqType = "";

	@Override
	public void initControls() {
		// TODO Auto-generated method stub
		webView = (WebView) findViewById(R.id.epoint_kaoqing_webView);
		kaoQing = (Button) findViewById(R.id.epoint_kaoqing_kaoqing);
		recards = (ListView) findViewById(R.id.epoint_kaoqing_recards);
		kaoQing.setBackgroundResource(R.drawable.button_login);
		kaoQing.setOnClickListener(this);
		webView.setBackgroundColor(Color.TRANSPARENT);
		adapter = new RecardsAdapter(this);
		recards.setAdapter(adapter);
		top_right_bt.setText("定位");
		top_right_bt.setOnClickListener(this);
		top_right_bt.setVisibility(View.VISIBLE);
		getLoc();
		// GetGPSInfoTask task = new GetGPSInfoTask(this, null);
		// MainService.addTask(task);
	}

	private void getLoc() {
		showDialog_wait("正获取您的位置...");
		reqType = GET_LOCATION;
		if (gpsHelper == null) {
			gpsHelper = new GPSHelper(this);
		}
		gpsHelper.getLocation();
	}

	public void showDialog_wait(String msg) {
		msg = msg == null ? "" : msg;
		if (msg.equals("")) {
			msg = "正在加载数据...";
		}
		m_Dialog = new ProgressDialog(this);
		m_Dialog.setMessage(msg);
		m_Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		// m_Dialog.setCancelable(false);
		m_Dialog.show();
	}

	/*
	 * private void showProgressDialog(String msg) { if (m_Dialog == null) {
	 * m_Dialog = new ProgressDialog(this);
	 * 
	 * m_Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	 * m_Dialog.setCancelable(false); } m_Dialog.setMessage(msg);
	 * m_Dialog.show(); }
	 */

	@Override
	public void onClick(View v) {
		if (v == kaoQing) {
			if (null == gpsInfo.getAddress() || "".equals(gpsInfo.getAddress())
					|| "null".equals(gpsInfo.getAddress())) {
				AlertHelp.ShowAlert(this, "考勤地点不能为空");
				return;
			}
			// 上报
			Log.i("tracy", "kaoQing");
			reqType = KAOQING;
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("obj", gpsInfo);
			showDialog_wait("正在签到...");
			KaoQingTask task = new KaoQingTask(this, map);
			MainService.addTask(task);
		} else if (v == top_right_bt) {
			getLoc();
		}
	}

	public void updateAddress(GPSInfo mGpsInfo) {
		System.out.println("sss" + System.currentTimeMillis());
		if (m_Dialog != null) {
			m_Dialog.dismiss();
		}
		gpsInfo = mGpsInfo;
		Log.i("tracy", "gpsInfo.getLocType()=" + gpsInfo.getLocType());
		String time = DBHelp.getConfigValue(this, ConfigKey.kaoqingTime);
		String key = com.epoint.mobileoa.personalized.epointcompany.config.ConfigKey.QDInfo
				+ fp.getUserguid();
		String bs = DBHelp.getConfigValue(this, key);
		String currTime = new SimpleDateFormat("yyyy/M/d").format(new Date());
		if (time.indexOf(currTime) == -1) {
			bs = null;
		}

		if (bs != null && !"".equals(bs)) {
			KaoQingDataHandler dataHandler = new KaoQingDataHandler();
			try {
				data = dataHandler.getData(bs);
			} catch (Exception e) {
				e.printStackTrace();
			}
			adapter.setList(data);
			adapter.notifyDataSetChanged();
		}
		// 定位失败处理
		if (gpsInfo.getLocType() != 61 && gpsInfo.getLocType() != 161) {
			ToastHelp.showToast(this, gpsInfo.getError());
		}
		if (null == gpsInfo.getRoadName() || "".equals(gpsInfo.getRoadName())) {
			ToastHelp.showToast(this, "定位失败，请重新定位！");
			// setWebViewData(bs != null && !"".equals(bs), time);
			// return;
		}

		setWebViewData(bs != null && !"".equals(bs), time);
		System.out.println("end" + System.currentTimeMillis());
	}

	@Override
	public void refresh(Object... param) {
		if (reqType.equals(KAOQING)) {

			if (param[1].toString().equals("false")) {
				AlertHelp.ShowAlert(this, "签到失败");
			} else {
				data = (List<KaoQingInfo>) param[1];
				String time = data.get(data.size() - 1).time;
				// String time = (String) param[1];
				DBHelp.setConfigValue(this, ConfigKey.kaoqingTime, time);
				setWebViewData(true, time);
				adapter.setList(data);
				adapter.notifyDataSetChanged();
			}

		}
		reqType = "";
		if (m_Dialog != null) {
			m_Dialog.dismiss();
		}
	}

	private void setWebViewData(boolean isKaoQing, String time) {
		String html = "<body><font  color="
				+ getYGColor()
				+ ">考勤人员姓名:</font><font  color="
				+ getBlackOrWhiteColor()
				+ ">"
				+ DBHelp.getConfigValue(this, ConfigKey.displayname)
				+ "</font><br><hr color='gray'>"
				+ "<font  color="
				+ getYGColor()
				+ ">考勤人员所属部门:</font><font  color="
				+ getBlackOrWhiteColor()
				+ ">"
				+ DBHelp.getUserOuname(this,
						DBHelp.getConfigValue(this, ConfigKey.userguid))
				+ "</font><br><hr color='gray'>";
		if (isKaoQing) {
			html = html + "<font  color=" + getYGColor()
					+ ">考勤时间:</font><font  color='lightgreen'>" + time
					+ "(已签到)</font><br><hr color='gray'>";
		} else {
			html = html
					+ "<font  color="
					+ getYGColor()
					+ ">考勤时间:</font><font  color="
					+ getBlackOrWhiteColor()
					+ ">"
					+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
							.format(new Date())
					+ "</font><br><hr color='gray'>";
		}
		html = html + "<font  color=" + getYGColor()
				+ ">考勤地点:</font><font  color='orange'>" + gpsInfo.getAddress()
				+ "</font><hr color='gray'>" + "</body>";

		webView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
	}

	@Override
	public String setTitle() {
		// TODO Auto-generated method stub
		return "考勤签到";
	}

	@Override
	protected void onDestroy() {
		Log.i("tracy", "onDestroy");
		gpsHelper.stop();
		super.onDestroy();
	}

	@Override
	public int getLayoutInt() {
		// TODO Auto-generated method stub
		return R.layout.epoint_kaoqing;
	}

	@Override
	public void onBack(GPSInfo gpsInfo) {
		updateAddress(gpsInfo);
		gpsHelper.stop();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "查看位置签到");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			Intent intent = new Intent(KaoQingView.this, BMap_GPS_Extent.class);
			startActivityForResult(intent, 1003);
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1003) {
			switch (resultCode) {
			case RESULT_OK:
				Bundle bundle = data.getBundleExtra("bundle");
				String address = bundle.getString("address");
				String name = bundle.getString("name");

				GPSInfo gpsInfo = new GPSInfo();
				gpsInfo.setName(name);
				gpsInfo.setRoadName(address);
				updateAddress(gpsInfo);
				break;

			default:
				break;
			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void refreshForNewTask(int TaskId,Object... param){
	}

}
